import React from 'react'
import { List, InputItem, NavBar, Icon, Grid } from 'antd-mobile'
import { connect } from 'react-redux'
import { sendMsg, getMsgList, recvMsg, readMsg } from '../../redux/chat.redux'
import { getChatId } from '../../util'
import QueueAnim from 'rc-queue-anim'

@connect(
  state => state,
  { sendMsg, getMsgList, recvMsg, readMsg }
)
class Chat extends React.Component {
  constructor () {
    super()
    this.state ={
      text: '',
      showEmoji: false
    }
    this.msgList = React.createRef()
  }
  componentDidMount () {
    // 如果是直接进来这个页面的，需要拉取聊天信息以及 socket 连接
    if (!this.props.chat.chatmsg.length) {
      this.props.getMsgList()
      this.props.recvMsg()
    }
    if (this.msgList.current) {
      this.msgList.current.scrollTo(0, this.msgList.current.scrollHeight)
    }
  }
  componentWillUnmount () {
    // 标记当前用户聊天列表的消息为已读，放在离开前清除一下，避免正在聊天的过程中新增的消息不能消除 read
    let to = this.props.match.params.user
    this.props.readMsg(to)
  }
  componentDidUpdate (prevProps) {
    // console.log(prevProps.chat.chatmsg.length, this.props.chat.chatmsg.length)
    // 这里算得不准，应该是拿当前这个聊天的 chatmsg 长度
    if (prevProps.chat.chatmsg.length !== this.props.chat.chatmsg.length) {
      if (this.msgList.current) {
        this.msgList.current.scrollTo(0, this.msgList.current.scrollHeight)
      }
    }
  }
  handleEmoji () {
    let showEmoji = !this.state.showEmoji
    this.setState({showEmoji})
    if (showEmoji) {
      this.fixCarousel()
    }
  }
  fixCarousel () {
    // 解决 ant design grid 组件的 bug
    setTimeout(function () {
      window.dispatchEvent(new Event('resize'))
    }, 0)
  }
  onSubmit (e) {
    if (e.keyCode === 13) {
      this.handleSubmit()
    }
  }
  handleSubmit () {
    let from = this.props.user._id
    let to = this.props.match.params.user
    let msg = this.state.text
    this.props.sendMsg({from, to, msg})
    this.setState({text: ''})
  }
  render () {
    let emoji = '😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍 😘 🙂 🤗 🤩 🤔 🤨 😐 😑 😶 🙄 😏 😣 😥 😮 🤐 😯 😪 😫 😴 😌 😛 😜 😝 😒 😓 😔 😕 🙃 🤑 😲 🙁 😖 😞 😟 😤 😢 😭 😦 😧 😨 😩 🤯 😬 😰 😱 😳 🤪 😵 😡 😠 🤬 😷 🤒 🤕 🤢 🤮 🤧 😇 🤠 🤡 🤥 🤫 🤭 🧐 🤓 😈 👿 👹 👺 💀 👻 👽 🤞 🖖 🤘 🖐 ✋ 👌 👍 👎 ✊ 👊 🤛 🤜 🤚 👋 🤟 👏 👐 🙌 🤲 🙏 🤝 🙅‍ 🙀'
      .split(' ')
      .filter(v => v) // 防止中间有多个空格的
      .map(v => ({text: v}))

    let Item = List.Item
    let userid = this.props.match.params.user // userid
    let users = this.props.chat.users
    if (!users[userid]) {
      return null
    }
    let chatid = getChatId(userid, this.props.user._id)
    let chatmsg = this.props.chat.chatmsg.filter(v => v.chatid === chatid)
    return (
      <div id='chat-page'>
        <div className='chat-navbar'>
          <NavBar icon={<Icon type='left'/>} onLeftClick={() => this.props.history.goBack()}>{users[userid].name}</NavBar>
        </div>
        <div className='chat-msg' ref={this.msgList}>
          <QueueAnim delay={100}>
            {chatmsg.map(v => {
              let avatar = require(`../../assets/image/${users[v.from].avatar}.png`)
              return v.from === userid ? (
                // 对方发过来的
                <List key={v._id}>
                  <Item thumb={avatar} >{v.content}</Item>
                </List>
              ) : (
                // 自己发送的
                <List key={v._id}>
                  <Item className='chat-me' extra={<img src={avatar} alt='avatar' />}>{v.content}</Item>
                </List>
              )
            })}
          </QueueAnim>
        </div>
        <div className='stick-footer'>
          <List>
            <InputItem
              placeholder='请输入'
              value={this.state.text}
              onChange={v => this.setState({text: v})}
              onKeyDown={e => this.onSubmit(e)}
              extra={
                <div>
                  <span style={{marginRight: '4px'}} onClick={() => this.handleEmoji()} role='img' aria-label='img'>😀</span>
                  <span onClick={this.handleSubmit.bind(this)}>发送</span>
                </div>
              } />
          </List>
          { this.state.showEmoji ? <Grid data={emoji} columnNum={9} carouselMaxRow={4} isCarousel={true} onClick={el => this.setState({text: this.state.text + el.text})}/> : null }
        </div>
      </div>
    )
  }
}

export default Chat